package com.peoplesay;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TableLayout;
import android.widget.TextView;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

public class PeopleSayGameActivity extends PeopleSayAbstractActivity {

	private int rndCat;
	private long mStartTime;
	private long clipStartTime;
	
	
	private Handler mHandler = new Handler();
	private TextView tvTime;
	private TextView tvScore;
	private int score;
	private static final int MY_START_GAME_DIALOG = 0;
	private static final int MY_END_GAME_DIALOG = 1;
	private static final int MY_SETTINGS_DIALOG = 2;
	
	
	
	private ArrayList visibleButtons = new ArrayList();
	
	
	@Override
	protected void initalizeListeners() {
		myClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				int viewId = (Integer) buttonMap.get(v.getId());
				if (rndCat == viewId) {
					score += 100;
				} else {
					score -= 50;
				}
				tvScore.setText(Integer.toString(score));
				playRand();

			}

		};

		buttonMap = new HashMap<Integer, Integer>();
		Drawable buttonPic = myResource.getDrawable(R.drawable.button_shape);

		for (int i = 0; i < categoryCount; i++) {
			Button b = (Button) findViewById(buttons[i]);
			b.setOnClickListener(myClickListener);
			buttonMap.put(buttons[i], i);
			b.getBackground().setAlpha(100);

		}

	}
	
	private void prepArrayList(int remove){
		
		visibleButtons.clear();
		for(int i = 0; i<categoryCount;i++){
			visibleButtons.add(i);
			findViewById(buttons[i]).setVisibility(View.VISIBLE);
		}
		visibleButtons.remove(remove);
	}
	
	
	private void updateButtons(){
		int rndIndex = rnd.nextInt(visibleButtons.size());
		findViewById(buttons[(Integer)(visibleButtons.get(rndIndex))]).setVisibility(View.INVISIBLE);
		visibleButtons.remove(rndIndex);
	}

	@Override
	protected void initalizeView() {
		setContentView(R.layout.game);
		mainLayoutView = (TableLayout) findViewById(R.id.mainTableLayout);
		mainLayoutView.setBackgroundDrawable(myResource
				.getDrawable(R.drawable.singlegirl));
		tvScore = (TextView) findViewById(R.id.textViewScore);
		tvTime = (TextView) findViewById(R.id.textViewTime);

	}

	@Override
	protected void start() {
		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			gameSetting = extras.getInt("EXTRA_GAME_SETTING");
			
		} else {
			gameSetting = 0;
		}
		
		showDialog(MY_START_GAME_DIALOG);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_game, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mg_switch:
			mHandler.removeCallbacks(mUpdateTimeTask);
			startActivity(new Intent(this, PeopleSayActivity.class));
			return true;
		case R.id.mg_settings:
			mHandler.removeCallbacks(mUpdateTimeTask);
			showDialog(MY_SETTINGS_DIALOG);
			return true;
		}
		return false;
	}

	private void playRand() {
		rndCat = rnd.nextInt(categoryCount);
		prepArrayList(rndCat);
		int soundFile = soundFiles[rndCat][rnd.nextInt(categoryFiles[rndCat])];
		if (soundFile != 0) {

			if (player != null) {
				try {
					player.stop();
					player.release();
				} catch (IllegalStateException e) {

				} finally {

				}
				player = null;
			}

			player = MediaPlayer.create(this, soundFile);
			player.setLooping(false);
			clipStartTime =  SystemClock.uptimeMillis();
			player.start();
			player.setOnCompletionListener(new OnCompletionListener() {
				public void onCompletion(MediaPlayer player) {
					player.release();
					player = null;
				}
			});
			player.setOnErrorListener(new OnErrorListener() {
				public boolean onError(MediaPlayer mp, int what, int extra) {

					return true;
				}

			});
		}

	}

	private void startGame()
	{
		mStartTime = SystemClock.uptimeMillis();
		mHandler.removeCallbacks(mUpdateTimeTask);
		mHandler.postDelayed(mUpdateTimeTask, 100);
		score = 0;
		tvScore.setText("0");
		playRand();
	}
	
	private Runnable mUpdateTimeTask = new Runnable() {
		public void run() {
			final long start = mStartTime;
			long millis = SystemClock.uptimeMillis() - start;
			int seconds = (int) (millis / 1000);
			long millisClip =  SystemClock.uptimeMillis() - clipStartTime;
			if (seconds/60 > 1) {
				mHandler.removeCallbacks(mUpdateTimeTask);
				showDialog(MY_END_GAME_DIALOG);
			} else {
				if (seconds < 10) {
					tvTime.setText("" + "0" + ":0" + seconds);
				} else {
					tvTime.setText("" + "0" + ":" + seconds);
				}
			
				
				if(millisClip/1000 > 1 && gameSetting == 0 && seconds%1==0 && visibleButtons.size()>1  ){
					updateButtons();
				}
				else if(millisClip/1000 > 2 && gameSetting == 1 && seconds%2==0 && seconds > 0 && visibleButtons.size()>3  ){
					updateButtons();
				}
				mHandler.postAtTime(this, start
						+ (( seconds + 1) * 1000));
			}
		}
	};

	@Override
	public void onStop() {
		mHandler.removeCallbacks(mUpdateTimeTask);
		tvTime.setText("0:00");
		super.onStop();
	}
	
	
	@Override
	public void onStart() {
		showDialog(MY_START_GAME_DIALOG);
		super.onStart();
	}


	private void goBackSoundboard() {
		startActivity(new Intent(this, PeopleSayActivity.class));
	}

	
	@Override 
	protected void onPrepareDialog(int id,Dialog dialog){


	
		switch(id){
		case MY_START_GAME_DIALOG:
			((AlertDialog)dialog).setMessage("Click Ok to play the game on "
					+ (String) settingsMap.get(gameSetting)
					+ " settings, try to guess which sound clip is playing by clicking the right button");
			break;
		case MY_END_GAME_DIALOG:
			Log.v("onPrepare","wrongCase");
			String status = "";

			if (score > 2500) {
				status = getString(R.string.scoreDialogStatus1);
			} else if (score > 2000) {
				status = getString(R.string.scoreDialogStatus2);
			} else if (score > 1500) {
				status = getString(R.string.scoreDialogStatus3);
			} else if (score > 1000) {
				status = getString(R.string.scoreDialogStatus4);
			} else if (score > 500) {
				status = getString(R.string.scoreDialogStatus5);
			} else {
				status = getString(R.string.scoreDialogStatus6);
			}
			((AlertDialog)dialog).setMessage(
					getString(R.string.endGameDialogMessage)
					+ Integer.toString(score) + "\n" + status);
			break;
		}
		super.onPrepareDialog(id, dialog);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case MY_START_GAME_DIALOG:


			score = 0;
			Log.v("gameStart",Integer.toString(gameSetting));
			return new AlertDialog.Builder(this)
					.setTitle("Play \"Shit People Say!\" Game")
					.setMessage("Click Ok to play the game on "
					+ (String) settingsMap.get(gameSetting)
					+ " settings, try to guess which sound clip is playing by clicking the right button")
					.setPositiveButton(getString(android.R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int arg1) {
									startGame();
								}
							}).create();
		

		case MY_END_GAME_DIALOG:
			String status = "";

			if (score > 2500) {
				status = getString(R.string.scoreDialogStatus1);
			} else if (score > 2000) {
				status = getString(R.string.scoreDialogStatus2);
			} else if (score > 1500) {
				status = getString(R.string.scoreDialogStatus3);
			} else if (score > 1000) {
				status = getString(R.string.scoreDialogStatus4);
			} else if (score > 500) {
				status = getString(R.string.scoreDialogStatus5);
			} else {
				status = getString(R.string.scoreDialogStatus6);
			}


			return new AlertDialog.Builder(this)
					.setTitle(getString(R.string.endGameDialogTitle))
					.setMessage(getString(R.string.endGameDialogMessage)
					+ Integer.toString(score) + "\n" + status)
					.setPositiveButton(getString(R.string.playagain),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int arg1) {
									startGame();
								}
							})
					.setNegativeButton(getString(R.string.backtosoundboard),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int arg1) {
									goBackSoundboard();
								}
							}).create();
			
		case MY_SETTINGS_DIALOG:
			return new AlertDialog.Builder(this)
			.setTitle(R.string.gameSettingTitle)
			.setItems(R.array.difficulty,
					new DialogInterface.OnClickListener() {
						public void onClick(
								DialogInterface dialoginterface, int i) {
							gameSetting = i;
							showDialog(MY_START_GAME_DIALOG);
						}
					}).create();

		}
		return null;
	}

}
